import * as API from '@/services';
import {
  KfBackendEnumPicker,
  DEFAULT_FORM_LAYOUT,
  KfBizQuickFormProps,
  KfFloatingContextProps,
  KfInput,
  KfQuickForm,
  KfTextArea,
  KfUpload,
  KfRichEditor,
  KfSelect,
} from 'kf-web-library';
import { Button, Col, Form, Row, Steps, Tabs } from 'antd';
import './index.less';
import React, { Fragment, FunctionComponent, useCallback, useMemo, useState } from 'react';
import JournalTempDocList from './JournalTempDocList';
import { DEFAULT_FORM_TAIL_LAYOUT } from '@kf-web-library/utils';
import KfMaterialUpload from '@/components/KfMaterialUpload';
import classNames from 'classnames';

const FormItem = Form.Item;
type QueryEntity = API.Journal;
type CreateEntity = API.Journal_Create;
type ModifyEntity = API.Journal_Modify;

type DataFormProps = {} & KfBizQuickFormProps & KfFloatingContextProps;

/**
 * Journal 表单
 */
const QuickForm: FunctionComponent<DataFormProps> = (props) => {
  const { formType, bizId, ...rest } = props;

  const isCustomAddOrEdit = formType === 'create' || (!!bizId && `${bizId}`.length > 8);

  const [langTabsActiveKey, setLangTabsActiveKey] = useState('cn');
  const [gnTabsActiveKey, setGnTabsActiveKey] = useState('a');
  const [form] = Form.useForm();

  const lugArr = useMemo(() => {
    const allowChangeLug = ['a', 'b', 'c'].includes(gnTabsActiveKey);
    return [
      { lable: '中文', key: 'cn', disabled: !allowChangeLug },
      { lable: '英文', key: 'en', disabled: !allowChangeLug },
    ];
  }, [gnTabsActiveKey]);

  const formLabelLayout = {
    labelCol: {
      flex: '0 0 80px',
    },
    wrapperCol: {
      flex: '1',
    },
  };

  const fieldNames = useMemo(() => {
    return {
      journalName: { label: '名称', cnName: 'journalNameCn', enName: 'journalNameEn' },
      journalSupervisorUnit: { label: '主管', cnName: 'journalSupervisorUnitCn', enName: 'journalSupervisorUnitEn' },
      journalHostUnit: { label: '主办', cnName: 'journalHostUnitCn', enName: 'journalHostUnitEn' },
      journalCn: { label: 'CN', cnName: 'journalCn', enName: 'journalCn' },
      journalPublicationCycle: { label: '刊期', cnName: 'journalPublicationCycle', enName: 'journalPublicationCycle' },
      journalCoverPathUrl: { label: '封面', cnName: 'journalCoverPathUrl', enName: 'journalCoverPathUrl' },
      journalLanguge: { label: '语种', cnName: 'journalLanguge', enName: 'journalLanguge' },
      journalEditor: { label: '主编', cnName: 'journalEditorCn', enName: 'journalEditorEn' },
      journalIssn: { label: 'ISSN', cnName: 'journalIssn', enName: 'journalIssn' },
      journalEissn: { label: 'eISSN', cnName: 'journalEissn', enName: 'journalEissn' },
      journalBreviaryIntroduction: { label: '期刊简介', cnName: 'journalBreviaryIntroductionCn', enName: 'journalBreviaryIntroductionEn' },
      authorGuidelinesContent: { label: '投稿指南', cnName: 'authorGuidelinesContentCn', enName: 'authorGuidelinesContentEn' },
      externalWebsite: {
        label: (
          <div>
            国外合作
            <br />
            出版商网站
          </div>
        ),
        cnName: 'externalWebsite',
        enName: 'externalWebsite',
      },
    };
  }, []);
  const getPublishingFormFields = useCallback((locale: string, active: boolean) => {
    return (
      <div key={locale} className={active ? '' : 'hidden-area'}>
        <Row>
          <Col span={12}>
            <FormItem
              name={fieldNames.journalPublicationCycle[`${locale}Name`]}
              label={fieldNames.journalPublicationCycle['label']}
              rules={[{ required: true }]}
            >
              <KfBackendEnumPicker.Select enumType={'JournalPublicationCycle'} readonly={!isCustomAddOrEdit} />
            </FormItem>
            <FormItem name={fieldNames.journalIssn[`${locale}Name`]} label={fieldNames.journalIssn['label']} rules={[{ required: true }]}>
              <KfInput readonly={!isCustomAddOrEdit} placeholder={'1111-1111'} />
            </FormItem>
            <FormItem name={fieldNames.journalEissn[`${locale}Name`]} label={fieldNames.journalEissn['label']} rules={[{ required: false }]}>
              <KfInput readonly={!isCustomAddOrEdit} placeholder={'1111-1111'} />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem name={fieldNames.journalLanguge[`${locale}Name`]} label={fieldNames.journalLanguge['label']} rules={[{ required: true }]}>
              <KfSelect
                readonly={!isCustomAddOrEdit}
                options={[
                  { label: '中文', value: 'cn' },
                  { label: '英文', value: 'en' },
                ]}
              />
            </FormItem>
            <FormItem name={fieldNames.journalCn[`${locale}Name`]} label={fieldNames.journalCn['label']} rules={[{ required: false }]}>
              <KfInput readonly={!isCustomAddOrEdit} placeholder={'11-1111/R'} />
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem shouldUpdate={true} noStyle={true}>
              {(formInstance) => {
                const journalLanguge = formInstance.getFieldValue('journalLanguge');
                const submitElements = (
                  <Form.Item label={null}>
                    <span style={{ display: 'inline-block', width: 80 }} />
                    <Button type="primary" htmlType="submit">
                      保存
                    </Button>
                  </Form.Item>
                );
                if (journalLanguge === 'en') {
                  return (
                    <>
                      <FormItem name={fieldNames.externalWebsite[`${locale}Name`]} label={fieldNames.externalWebsite['label']} rules={[{ required: false }]}>
                        <KfTextArea rows={2} placeholder="https://xxx.com" />
                      </FormItem>
                      {submitElements}
                    </>
                  );
                } else if (isCustomAddOrEdit) {
                  return submitElements;
                }
                return null;
              }}
            </FormItem>
          </Col>
        </Row>
      </div>
    );
  }, []);
  const getBaseFormFields = useCallback(
    (locale: string, active: boolean) => {
      return (
        <div key={locale} className={active ? '' : 'hidden-area'}>
          <Row>
            <Col span={12}>
              <FormItem name={fieldNames.journalName[`${locale}Name`]} label={fieldNames.journalName['label']} rules={[{ required: locale === 'cn' }]}>
                <KfInput readonly={!isCustomAddOrEdit} />
              </FormItem>
              <FormItem
                name={fieldNames.journalSupervisorUnit[`${locale}Name`]}
                label={fieldNames.journalSupervisorUnit['label']}
                rules={[{ required: false }]}
              >
                <KfInput readonly={!isCustomAddOrEdit} />
              </FormItem>
              <FormItem name={fieldNames.journalHostUnit[`${locale}Name`]} label={fieldNames.journalHostUnit['label']} rules={[{ required: false }]}>
                <KfInput readonly={!isCustomAddOrEdit} />
              </FormItem>
              <FormItem name={fieldNames.journalEditor[`${locale}Name`]} label={fieldNames.journalEditor['label']} rules={[{ required: false }]}>
                <KfInput readonly={!isCustomAddOrEdit} />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                name={fieldNames.journalCoverPathUrl[`${locale}Name`]}
                label={fieldNames.journalCoverPathUrl['label']}
                rules={[{ required: false }]}
                help={'尺寸：128*182，大小：建议大小不超过50k，格式：支持上传jpg、jpeg、png格式'}
              >
                <KfMaterialUpload.Avatar materialType={'IMG'} />
              </FormItem>
            </Col>
          </Row>

          <Form.Item label={null}>
            <span style={{ display: 'inline-block', width: 80 }} />
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </div>
      );
    },
    [form.getFieldValue('languageType')],
  );

  const getIntroFormFields = useCallback((locale: string, active: boolean) => {
    return (
      <div key={locale} className={active ? '' : 'hidden-area'}>
        <FormItem name={fieldNames.journalBreviaryIntroduction[`${locale}Name`]} label={null} rules={[{ required: false }]}>
          <KfTextArea readonly={!isCustomAddOrEdit} rows={20} />
        </FormItem>
        {isCustomAddOrEdit && (
          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        )}
      </div>
    );
  }, []);

  const getGuideFormFields = useCallback((locale: string, active: boolean) => {
    return (
      <div key={locale} className={active ? '' : 'hidden-area'}>
        <FormItem name={fieldNames.authorGuidelinesContent[`${locale}Name`]} label={null} rules={[{ required: false }]}>
          <KfRichEditor />
        </FormItem>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
        </Form.Item>
      </div>
    );
  }, []);

  return (
    <KfQuickForm
      formType={formType}
      formProps={{
        className: 'journal-form',
        form,
        ...formLabelLayout,
        requiredMark: isCustomAddOrEdit,
      }}
      whetherCloseWrapFloating={false}
      submitButtonText={false}
      defaultQueryRequest={() =>
        API.queryJournal(bizId!).then((resp) => {
          if (resp.flag) {
            resp.data = {
              ...resp.data,
              authorGuidelinesContentCn: resp.data?.authorGuidelinesContentCn || '',
              authorGuidelinesContentEn: resp.data?.authorGuidelinesContentEn || '',
            };
          }
          return new Promise((resolve) => resolve(resp));
        })
      }
      onValidateFailed={(errorInfo) => {
        const firstErrorField = errorInfo.errorFields[0].name[0] as string;
        // 基础信息tab包含的字段
        const baseInfoFields = [
          fieldNames.journalName.cnName,
          fieldNames.journalName.enName,
          fieldNames.journalSupervisorUnit.cnName,
          fieldNames.journalSupervisorUnit.enName,
          fieldNames.journalHostUnit.cnName,
          fieldNames.journalHostUnit.enName,
          fieldNames.journalEditor.cnName,
          fieldNames.journalEditor.enName,
          fieldNames.journalCoverPathUrl.cnName,
          fieldNames.journalCoverPathUrl.enName,
        ];

        // 出版信息tab包含的字段
        const publishInfoFields = [
          fieldNames.journalPublicationCycle.cnName,
          fieldNames.journalPublicationCycle.enName,
          fieldNames.journalIssn.cnName,
          fieldNames.journalIssn.enName,
          fieldNames.journalEissn.cnName,
          fieldNames.journalEissn.enName,
          fieldNames.journalCn.cnName,
          fieldNames.journalCn.enName,
          fieldNames.journalLanguge.cnName,
          fieldNames.journalLanguge.enName,
          fieldNames.externalWebsite.cnName,
          fieldNames.externalWebsite.enName,
        ];

        // 期刊简介tab包含的字段
        const introFields = [fieldNames.journalBreviaryIntroduction.cnName, fieldNames.journalBreviaryIntroduction.enName];

        // 投稿指南tab包含的字段
        const guideFields = [fieldNames.authorGuidelinesContent.cnName, fieldNames.authorGuidelinesContent.enName];

        // 判断错误字段属于哪个tab，并切换到对应tab
        if (baseInfoFields.includes(firstErrorField)) {
          setGnTabsActiveKey('a');
        } else if (publishInfoFields.includes(firstErrorField)) {
          setGnTabsActiveKey('e');
        } else if (introFields.includes(firstErrorField)) {
          setGnTabsActiveKey('b');
        } else if (guideFields.includes(firstErrorField)) {
          setGnTabsActiveKey('c');
        }
      }}
      submitRequest={{
        create: (formValues) =>
          API.createJournal({
            ...formValues,
            languageType: formValues.journalLanguge.toUpperCase(),
          } as CreateEntity),
        modify: (formValues) =>
          API.patchJournal({
            journalCoverPathUrl: formValues.journalCoverPathUrl,
            authorGuidelinesContentCn: formValues.authorGuidelinesContentCn,
            authorGuidelinesContentEn: formValues.authorGuidelinesContentEn,
            externalWebsite: formValues.externalWebsite,
            id: bizId,
          } as ModifyEntity),
      }}
      {...rest}
    >
      <Tabs
        className={classNames({ 'journal-disable-tabs': !['a', 'b', 'c'].includes(gnTabsActiveKey) })}
        activeKey={['a', 'b', 'c'].includes(gnTabsActiveKey) ? langTabsActiveKey : 'undefined'}
        defaultValue={'undefined'}
        onChange={(key) => setLangTabsActiveKey(key)}
        items={lugArr.map((g) => {
          return {
            label: g.lable,
            key: g.key,
            disabled: g.disabled,
            forceRender: true,
            className: 'journal-hide-tabpane',
            children: null,
          };
        })}
      />

      <Tabs
        tabPosition="left"
        activeKey={gnTabsActiveKey}
        onChange={(key) => setGnTabsActiveKey(key)}
        items={[
          {
            label: '基础信息',
            key: 'a',
            className: 'journal-tabpane',
            forceRender: true,
            children: (
              <>
                {lugArr.map((g) => {
                  return getBaseFormFields(g.key, g.key === langTabsActiveKey);
                })}
              </>
            ),
          },
          {
            label: '出版信息',
            key: 'e',
            className: 'journal-tabpane',
            forceRender: true,
            children: (
              <>
                {lugArr.map((g) => {
                  return getPublishingFormFields(g.key, g.key === langTabsActiveKey);
                })}
              </>
            ),
          },
          {
            label: '期刊简介',
            key: 'b',
            forceRender: true,
            children: (
              <>
                {lugArr.map((g) => {
                  return getIntroFormFields(g.key, g.key === langTabsActiveKey);
                })}
              </>
            ),
          },
          {
            label: '投稿指南',
            key: 'c',
            forceRender: true,
            children: (
              <>
                {lugArr.map((g) => {
                  return getGuideFormFields(g.key, g.key === langTabsActiveKey);
                })}
              </>
            ),
          },
          {
            label: '模版文档',
            key: 'd',
            forceRender: true,
            children: (
              <>
                <JournalTempDocList journalId={bizId} locale={langTabsActiveKey} />
              </>
            ),
          },
        ]}
      />
    </KfQuickForm>
  );
};

export default QuickForm;
